import React, { useLayoutEffect, useRef, useState } from 'react';
import { View, Text, ScrollView, router, publishDps, hideMenuButton } from '@ray-js/ray';
import clsx from 'clsx';
import { useProps } from '@ray-js/panel-sdk';
import { Picker, ClockInfoSet } from '@/components';
import { getCachedSystemInfo } from '@/api/getCachedSystemInfo';
import Strings from '@/i18n';

import { useSelector } from 'react-redux';
import { updateClockName } from '@/redux/modules/cloudStateSlice';
import { ReduxState, useAppDispatch } from '@/redux';
import { NavBar, Dialog, DialogInstance } from '@ray-js/smart-ui';
import { encodeClock, decodeClock } from '@/components/AlarmList/util';

import { saveCloudData } from '@/api';
import styles from './index.module.less';
import { checkRepeat } from './util';

const { safeArea } = getCachedSystemInfo();

const { height } = safeArea;

const getOriginData = (data: Record<string, any>) => {
  return {
    status: data.status,
    startTime: data.startTime,
    startTimeObj: {
      hour: Math.floor(data.startTime / 60),
      minute: data.startTime % 60,
    },
    repeat: data.repeat,
    weekRepeatPower: data.weekRepeatPower,
    hue: data.hue,
    saturation: 1000,
    value: data.vue,
    voice: data.voice,
    music: data.music,
    code: data.code,
    colour: {
      hue: data.hue,
      saturation: 1000,
      value: data.value,
    },
  };
};

export function ClockEdit({ location }) {
  const { query } = location;

  const enabledDelete = query.enabledDelete === 'true';

  const clockStr = useProps(props => props[query.code || 'clock_1']);

  const {
    clock_1: clock1,
    clock_2: clock2,
    clock_3: clock3,
    clock_4: clock4,
    clock_5: clock5,
    clock_6: clock6,
    clock_7: clock7,
  } = useProps(props => props);

  const list = [clock1, clock2, clock3, clock4, clock5, clock6, clock7];

  const data = decodeClock(clockStr, query.code || 'clock_1');

  const orginData = getOriginData(data);

  useLayoutEffect(() => {
    hideMenuButton();
  }, []);

  const [scrollEnabled, setScrollEnabled] = useState(true);
  const dispatch = useAppDispatch();

  const [weekRepeat, setWeekRepeat] = useState(orginData.weekRepeatPower);

  const [weeks, setWeeks] = useState<number[]>(orginData.repeat);

  const [volumeSet, setVolumeSet] = useState(orginData.voice);

  const [startTime, setStartTime] = useState(orginData.startTimeObj);

  const [colour, setColour] = useState(orginData.colour);

  const [music, setMusic] = useState(orginData.music);

  const { clockNames } = useSelector((state: ReduxState) => state.cloudState);

  const [showDialog, setShowDialog] = useState(false);

  const [name, setName] = useState(clockNames[query.code || 'clock_1']);

  const onConfirm = e => {
    setName(e.detail.value);
  };

  const onClose = e => {
    saveCloudData({
      code: query.code || 'clock_1',
      value: name,
    });
    dispatch(updateClockName({ [query.code || 'clock_1']: name }));

    setShowDialog(false);
  };

  const setClockName = name => {
    setShowDialog(true);
    setName(name);
  };

  const onClickLeft = () => {
    router.back();
  };

  const clockList = [
    {
      ...decodeClock(clock1, 'clock_1'),
      title: clockNames['clock_1'] || 'Clock 1',
    },
    {
      ...decodeClock(clock2, 'clock_2'),
      title: clockNames['clock_2'] || 'Clock 2',
    },
    {
      ...decodeClock(clock3, 'clock_3'),
      title: clockNames['clock_3'] || 'Clock 3',
    },
    {
      ...decodeClock(clock4, 'clock_4'),
      title: clockNames['clock_4'] || 'Clock 4',
    },
    {
      ...decodeClock(clock5, 'clock_5'),
      title: clockNames['clock_5'] || 'Clock 5',
    },
    {
      ...decodeClock(clock6, 'clock_6'),
      title: clockNames['clock_6'] || 'Clock 6',
    },
    {
      ...decodeClock(clock7, 'clock_7'),
      title: clockNames['clock_7'] || 'Clock 7',
    },
  ];

  const showList = clockList.filter(
    (item, index) => (!item.unSetted || index < 3) && item.status && item.code !== query.code
  );

  const saveClock = () => {
    const params = {
      startTime: startTime.hour * 60 + startTime.minute,
      repeat: weeks,
      weekRepeatPower: weekRepeat,
      ...colour,
      voice: volumeSet,
      music,
      status: true,
      code: query.code || 'clock_1',
    };

    const confict = checkRepeat(params, showList);

    if (confict.length) {
      DialogInstance.alert({
        selector: '#smart-dialog2',
        message: Strings.formatValue('clock_conflict', confict.join(',')),
      }).then(() => {
        // on close
      });

      return;
    }

    const res = encodeClock(params);

    publishDps({
      [query.code || 'clock_1']: res,
    });

    router.back();
  };

  return (
    <View className={styles.view}>
      <NavBar
        leftArrow
        onClickLeft={onClickLeft}
        title=""
        className={styles.navBar}
        rightText={enabledDelete ? Strings.getLang('delete') : ''}
        rightTextClass={styles.deleteText}
        customClass={styles.borBot}
        onClickRight={() => {
          if (!enabledDelete) {
            return;
          }
          publishDps({
            [query.code || 'clock_1']: '00',
          });
          onClickLeft();
        }}
        onClickRightText={() => {
          if (!enabledDelete) {
            return;
          }
          publishDps({
            [query.code || 'clock_1']: '00',
          });
          onClickLeft();
        }}
      />
      <ScrollView
        scrollY={scrollEnabled}
        refresherTriggered
        className={clsx(styles.slideUpContent)}
        style={{
          height: `calc(${height}px - 130rpx)`,
          paddingInline: '20rpx',
        }}
      >
        <View
          style={{
            marginTop: 10,
          }}
        >
          <Text
            onClick={() => {
              setClockName(clockNames[query.code || 'clock_1']);
            }}
            className={styles.title}
          >
            {clockNames[query.code || 'clock_1'] ||
              `Alarm ${(query.code || 'clock_1').slice(6, 7)}`}
          </Text>

          <View className={styles.PickerBox}>
            <Picker
              time={startTime}
              handlePickerChange={val => {
                setStartTime(val);
              }}
              is24
            />
          </View>

          <ClockInfoSet
            colour={colour}
            voice={volumeSet}
            weeks={weeks}
            weekRepeat={weekRepeat}
            music={music}
            setMusic={setMusic}
            setWeekRepeat={setWeekRepeat}
            setWeeks={setWeeks}
            onChange={setColour}
            changeVoice={setVolumeSet}
            setScrollEnabled={setScrollEnabled}
          />
        </View>
        <View
          style={{
            height: '200rpx',
            width: '200rpx',
          }}
        />
      </ScrollView>

      <View className={styles.saveBtnBox} onClick={saveClock}>
        <View className={styles.saveBtn}>
          <Text>{Strings.getLang('confirm')}</Text>
        </View>
      </View>

      <Dialog
        onConfirm={onConfirm}
        onCancel={() => {
          setShowDialog(false);
        }}
        onClose={onClose}
        showCancelButton
        confirmButtonText={Strings.getLang('confirm')}
        cancelButtonText={Strings.getLang('cancel')}
        show={showDialog}
        value={name}
        title={Strings.getLang('nameEdit')}
      />

      <Dialog id="smart-dialog2" />
    </View>
  );
}

export default ClockEdit;
